package pl.cezary.butler.walili.server.db;

//import WaliLi.Serwer.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import pl.cezary.butler.walili.server.config.ServerConfiguration;


/*
 * @author Przemysław Bałdyga
 */
public class DatabaseMySql extends Database {

    private static final Logger log = Logger.getLogger("BazaDanychMySql");
    private static final ServerConfiguration CONFIG = ServerConfiguration.getInstance();
    private String HOST = CONFIG.getDbServer();
    private String LOGIN = CONFIG.getDbLogin();
    private String HASLO = CONFIG.getDbPassword();
    private String BAZA = CONFIG.getDbName();
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static DatabaseMySql instancja = null;
    private Properties props;

    {
    }

    public static DatabaseMySql getInstance() {
        return (instancja == null) ? instancja = new DatabaseMySql() : instancja;
    }

    public DatabaseMySql(String host, String baza, String login, String haslo) {
        HOST = (host == null || host.length() == 0) ? HOST : host;
        LOGIN = (login == null || login.length() == 0) ? LOGIN : login;
        BAZA = (baza == null || baza.length() == 0) ? BAZA : baza;
        HASLO = (haslo == null || haslo.length() == 0) ? HASLO : haslo;
        prepareProps();
        polacz();
    }

    public DatabaseMySql() {
        prepareProps();
        polacz();
    }

    private void prepareProps() {
        props = new Properties();
        props.setProperty("useUnbufferedInput", "false");
        props.setProperty("autocommit", "false");
        props.setProperty("HOST", HOST);
        props.setProperty("DBNAME", BAZA);
        props.setProperty("user", LOGIN);
        props.setProperty("password", HASLO);
    }

    protected Connection createConnection() throws RuntimeException {
        try {

            return DriverManager.getConnection(getConnectionUrl(), props);
        } catch (SQLException ex) {
            log.log(Level.SEVERE, "Problem podczas tworzenia polaczenia z bd", ex);
            throw new RuntimeException(ex);
        }
    }

    @Override
    protected String getConnectionUrl() {
        return "jdbc:mysql://" + HOST + "/" + BAZA;
    }

    @Override
    protected String getPassword() {
        return HASLO;
    }

    @Override
    protected String getUsername() {
        return LOGIN;
    }

    @Override
    protected Class<? extends java.sql.Driver> getDriverClass() throws RuntimeException {
        try {

            java.sql.Driver d = (java.sql.Driver) Class.forName(DRIVER).newInstance();

            log.finest("Pobrano sterownik MySql");
            return d.getClass();
        } catch (Exception ex) {
            log.log(Level.SEVERE, "Problem z pobraniem sterownika", ex);
            throw new RuntimeException(ex);
        }
    }
}
